﻿using System;
using System.IO;

namespace Sharp.Infrastructure.StringEncode
{
    /// <summary>
    /// 文字编码处理类
    /// </summary>
    public class StringEncode
    {
        /// <summary>
        /// 获取编码
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string[] GetEncodings(Stream stream)
        {
            try
            {
                int lang = 3;//
                //用指定的语参数实例化Detector
                Detector det = new Detector(lang);
                //初始化
                MyCharsetDetectionObserver cdo = new MyCharsetDetectionObserver();
                det.Init(cdo);


                byte[] buf = new byte[1024];
                int len;
                bool done = false;
                bool isAscii = true;

                while ((len = stream.Read(buf, 0, buf.Length)) != 0)
                {
                    // 探测是否为Ascii编码
                    if (isAscii)
                        isAscii = det.isAscii(buf, len);

                    // 如果不是Ascii编码，并且编码未确定，则继续探测
                    if (!isAscii && !done)
                        done = det.DoIt(buf, len, false);
                }
               
                //调用DatEnd方法，
                //如果引擎认为已经探测出了正确的编码，
                //则会在此时调用ICharsetDetectionObserver的Notify方法
                det.DataEnd();

                if (cdo.Charset != null)
                {
                    return new string[] { cdo.Charset };
                }
                else
                {
                    return det.getProbableCharsets();
                }
            }
            catch (Exception ex )
            {
                throw ex;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
    }
    internal class MyCharsetDetectionObserver : ICharsetDetectionObserver
    {
        public string Charset = null;

        public void Notify(string charset)
        {
            this.Charset = charset;
        }
    }

}